package org.springblade.modules.platform.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import org.springblade.modules.platform.dto.DeptInfoTableDTO;
import org.springblade.modules.platform.entity.DeptInfoTable;
import org.springblade.modules.platform.props.HuatengProperties;
import org.springblade.modules.platform.service.IDeptInfoTableService;
import org.springblade.modules.platform.vo.*;
import org.springblade.modules.platform.vo.enums.DeptCategoryEnum;
import org.springblade.modules.platform.vo.enums.MeasureTypeEnum;
import org.springblade.modules.platform.vo.enums.UntilTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springblade.core.tool.api.R;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@AllArgsConstructor
@RequestMapping("/service-huateng-sxdb/deptInfoTabl")
@Api(value = "", tags = "测量链管理")
public class DeptInfoTableController {
    private final IDeptInfoTableService iDeptInfoTableService;
    private final HuatengProperties huatengProperties;
    private static RestTemplate restTemplate = new RestTemplate();


    @GetMapping("/info")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "点击左边树", notes = "")
    public R<List<DeptInfoTableVO>> getInfo(@RequestParam(value = "id",required = false) Integer id,
                                            @RequestParam(value = "deptName",required = false) String deptName,
                                            @RequestParam(value = "deptCategory",required = false) Integer deptCategory) {
        List<DeptInfoTable> list;
        QueryWrapper<DeptInfoTable> queryWrapper = new QueryWrapper<>();
        if(id!=null){
            queryWrapper.lambda().eq(DeptInfoTable::getParentId,id);
        }
        if(!StringUtils.isEmpty(deptName)){
            queryWrapper.lambda().like(DeptInfoTable::getDeptName,deptName);

        }
        if(deptCategory!=null){
            queryWrapper.lambda().eq(DeptInfoTable::getDeptCategory,deptCategory);

        }
        queryWrapper.lambda().eq(DeptInfoTable::getIsDeleted,0);
        list = iDeptInfoTableService.list(queryWrapper);
        List<DeptInfoTableVO> collect = list.stream().map(this::apply).collect(Collectors.toList());
        return R.data(collect);
    }

    @PostMapping(value = "/install")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "新增", notes = "传入deptInfoTableDTO")
    public R add(@RequestBody DeptInfoTableDTO deptInfoTableDTO){
        iDeptInfoTableService.insertDeptInfoTable(deptInfoTableDTO);
        return R.success("成功");
    }
    @DeleteMapping("/remove/{id}")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "删除设备", notes = "传入deviceIds")
    public R remove(@PathVariable Integer id){
        DeptInfoTable byId = iDeptInfoTableService.getById(id);
        if(byId.getDeptCategory()==DeptCategoryEnum.MEASURING.getCode()){
            HttpEntity<JSONObject> httpEntity = new HttpEntity<>(null,new HttpHeaders());
            restTemplate.exchange(huatengProperties.getRemove()+id, HttpMethod.POST, httpEntity, String.class);
        }
        iDeptInfoTableService.removeDeptInfo(id);
        return R.success("成功");
    }

    @PutMapping(value = "/update")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "编辑", notes = "传入deptInfoTableDTO")
    public R edit(@RequestBody DeptInfoTableDTO deptInfoTableDTO) {
        iDeptInfoTableService.updateDeptInfo(deptInfoTableDTO);
        return R.success("成功");
    }



    @GetMapping(value = "/getBachinfo/{id}")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "详细", notes = "id")
    public  R<DeptInfoTableInfoVO> getBachinfo(@PathVariable("id") Integer id) {
        return R.data(iDeptInfoTableService.getDeptInfoTableInfo(id));
    }
    @GetMapping(value = "/untilType")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "单位类型下拉框", notes = "deptId")
    public  R<Map<Integer,String>> getUntilType() {
        Map<Integer, String> mapResult = new HashMap<>();
        Arrays.stream(UntilTypeEnum.values()).forEach(untilTypeEnum -> mapResult.put(untilTypeEnum.getCode(), untilTypeEnum.getMsg()));
        return R.data(mapResult);
    }
    @GetMapping(value = "/measureType")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "测量链类型下拉框", notes = "deptId")
    public  R<Map<Integer,String>> getMeasureType() {
        Map<Integer, String> mapResult = new HashMap<>();
        Arrays.stream(MeasureTypeEnum.values()).forEach(measureTypeEnum -> mapResult.put(measureTypeEnum.getCode(), measureTypeEnum.getMsg()));
        return R.data(mapResult);
    }
    @GetMapping(value = "/previousMeasureType/{id}")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "获取上一个测台", notes = "deptId")
    public  R<DeptInfoTable> previousMeasureType(@RequestParam(value = "id",required = false)  Integer id) {
        return R.data(iDeptInfoTableService.previousMeasureType(id));
    }
    @GetMapping(value = "/MeasureTypeList")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "获取测台下拉框", notes = "")
    public  R<List<DeptInfoTable>> MeasureTypeList(Integer id) {
        return R.data(iDeptInfoTableService.getMeasureTypeList(id));
    }
    @GetMapping("/tree")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "树", notes = "")
    public R<List<DeptInfoTableTreeVO>> tree() {
        List<DeptInfoTable> list = iDeptInfoTableService.list(Wrappers.<DeptInfoTable>query().lambda().eq(DeptInfoTable::getIsDeleted,0).orderByAsc(DeptInfoTable::getSort));
        if(CollectionUtils.isEmpty(list)){
           return R.data(null);
        }
        List<DeptInfoTableTreeVO> collect = list.stream().map(x -> DeptInfoTableTreeVO.builder().deptName(x.getDeptName()).deptCategory(x.getDeptCategory()).remark(x.getRemark()).parentId(Long.parseLong(x.getParentId().toString())).id(Long.parseLong(x.getId().toString())).build()).collect(Collectors.toList());
        List<DeptInfoTableTreeVO> collect1 = collect.stream().filter(m -> m.getParentId()==0).peek((m) -> m.setChildrenList(getChildrens(m, collect))).collect(Collectors.toList());
        return R.data(collect1);
    }
    private static List<DeptInfoTableTreeVO> getChildrens(DeptInfoTableTreeVO root, List<DeptInfoTableTreeVO> all) {
        return all.stream().filter(m -> Objects.equals(m.getParentId(), root.getId())).peek(
                (m) -> m.setChildrenList(getChildrens(m, all))
        ).collect(Collectors.toList());
    }


    private DeptInfoTableVO apply(DeptInfoTable x) {
        DeptInfoTableVO deptInfoTableVO = new DeptInfoTableVO();
        Long count = iDeptInfoTableService.count(Wrappers.<DeptInfoTable>query().lambda().eq(DeptInfoTable::getParentId, x.getId()));
        BeanUtils.copyProperties(x, deptInfoTableVO);
        switch (Objects.requireNonNull(DeptCategoryEnum.getEnum(x.getDeptCategory()))) {
            case DEPT:
                break;
            case COMPANY:
                DeptTypeInfoVO deptTypeInfoVO = iDeptInfoTableService.selectDeptTypeInfo(x.getId());
                deptInfoTableVO.setDeptTypeInfoVO(deptTypeInfoVO);
                break;
            case PLATFORM:
                DeptBenchInfoVO deptBenchInfoVO = iDeptInfoTableService.selectDeptBenchInfo(x.getId());
                deptInfoTableVO.setDeptBenchInfoVO(deptBenchInfoVO);
                break;
            case MEASURING:
                DeptMeasuringInfoVO deptMeasuringInfoVO = iDeptInfoTableService.selectDeptMeasuringInfo(x.getId());
                deptInfoTableVO.setDeptMeasuringInfoVO(deptMeasuringInfoVO);
                break;
        }
        deptInfoTableVO.setSubsetNumber(count);
        return deptInfoTableVO;
    }
}
